namespace SubSonic
{
    using SubSonic.CodeGenerator;
    using SubSonic.Utilities;
    using System;
    using System.CodeDom;
    using System.IO;
    using System.Text;
    using System.Web.Compilation;
    using System.Web.Hosting;

	public class BuildProvider : System.Web.Compilation.BuildProvider
    {
        public override void GenerateCode(AssemblyBuilder assemblyBuilder)
        {
            Utility.WriteTrace("Invoking BuildProvider");
            DataService.LoadProviders();
            ICodeLanguage language = new CSharpCodeLanguage();
            DirectoryInfo info = new DirectoryInfo(HostingEnvironment.ApplicationPhysicalPath + @"\App_Code");
            if (info.GetFiles("*.vb").Length > 0)
            {
                language = new VBCodeLanguage();
            }
            StringBuilder builder = new StringBuilder(language.DefaultUsingStatements);
            TurboCompiler compiler = new TurboCompiler();
            foreach (DataProvider provider in DataService.Providers)
            {
                Utility.WriteTrace("Creating code for " + provider.Name);
                string[] tableNames = DataService.GetTableNames(provider.Name);
                string[] viewNames = DataService.GetViewNames(provider.Name);
                foreach (string str in tableNames)
                {
                    TurboTemplate template = CodeService.BuildClassTemplate(str, language, provider);
                    compiler.AddTemplate(template);
                    TurboTemplate template2 = CodeService.BuildODSTemplate(str, language, provider);
                    compiler.AddTemplate(template2);
                }
                foreach (string str2 in viewNames)
                {
                    TurboTemplate template3 = CodeService.BuildViewTemplate(str2, language, provider);
                    compiler.AddTemplate(template3);
                }
                compiler.AddTemplate(CodeService.BuildSPTemplate(language, provider));
            }
            if (DataService.Providers.Count > 0)
            {
                compiler.AddTemplate(CodeService.BuildStructsTemplate(language, DataService.Provider));
            }
            foreach (TurboTemplate template4 in compiler.Templates)
            {
                template4.AddUsingBlock = false;
            }
            compiler.Run();
            foreach (TurboTemplate template5 in compiler.Templates)
            {
                builder.Append(template5.FinalCode);
            }
            assemblyBuilder.AddCodeCompileUnit(this, new CodeSnippetCompileUnit(builder.ToString()));
        }
    }
}

